﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<style>
    .search-box {
        padding: 15px;
        background-color: #fff;
        margin-bottom: 15px;
        border-radius: 2px;
        box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
    }
    .page-container {
        padding: 15px;
        background-color: #fff;
        border-radius: 2px;
        box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
    }
    .layui-form-item {
        margin-bottom: 10px;
    }
    .layui-btn-group {
        margin-right: 5px;
    }
    .layui-table {
        margin-top: 0;
    }
    .layui-table th {
        font-weight: bold;
        background-color: #f8f8f8;
    }
    .layui-btn-sm {
        height: 28px;
        line-height: 28px;
        padding: 0 10px;
        font-size: 12px;
    }
    .layui-table-cell {
        height: auto;
        line-height: 28px;
    }
    .layui-form-label {
        padding: 8px 10px;
    }
    .layui-input, .layui-select {
        height: 32px;
    }
    .layui-btn {
        height: 32px;
        line-height: 32px;
    }
</style>
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<body class="layui-bg-gray">
    <div class="search-box">
        <div class="layui-form">
            <div class="layui-form-item" style="margin-bottom: 0;">
                <label class="layui-form-label">报工类型:</label>
                <div class="layui-input-inline">
                    <select name="quiz1" id="reportingType" lay-filter="reportingType">
                        <option value="">请选择报工类型</option>
                        <option value="自行报工">自行报工</option>
                        <option value="统一报工">统一报工</option>
                    </select>
                </div>
                <label class="layui-form-label">工作站名称:</label>
                <div class="layui-input-inline">
                    <input type="text" id="workstationName" name="workstationName" placeholder="请输入工作站名称" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">生产工单编号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="productionWorkOrderCode" name="productionWorkOrderCode" placeholder="请输入生产工单编号" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">产品物料编号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="productMaterialCode" name="productMaterialCode" placeholder="请输入产品物料编号" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">产品物料名称:</label>
                <div class="layui-input-inline">
                    <input type="text" id="productMaterialName" name="productMaterialName" placeholder="请输入产品物料名称" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">报工人:</label>
                    <div class="layui-input-inline">
                        <input type="text" id="reporter" name="reporter" placeholder="请输入报工人" autocomplete="off" class="layui-input">
                    </div>
                    <label class="layui-form-label">记录人:</label>
                    <div class="layui-input-inline">
                        <input type="text" id="recorder" name="recorder" placeholder="请输入记录人" autocomplete="off" class="layui-input">
                    </div>
                    <label class="layui-form-label">状态:</label>
                    <div class="layui-input-inline">
                        <select name="quiz1" id="states">
                            <option value="">请选择状态</option>
                            <option value="1">草稿</option>
                            <option value="2">审核中</option>
                            <option value="3">已完成</option>
                            <option value="4">已拒绝</option>
                        </select>
                    </div>
                    <button class="layui-btn" lay-submit lay-filter="searchForm">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="reset" class="layui-btn layui-btn-primary" onclick="resetForm()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                    <button type="button" class="layui-btn layui-btn-danger" id="batchDeleteBtn">
                        <i class="layui-icon layui-icon-delete"></i> 批量删除
                    </button>
                    <button type="button" class="layui-btn layui-bg-blue" onclick="addProductionReport()">
                        <i class="layui-icon layui-icon-addition"></i> 新增
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div class="page-container">
        @Html.AntiForgeryToken()
        <table class="layui-table" lay-size="lg" id="dataTable" lay-filter="dataTable">
            <thead>
                <tr>
                    <th style="width: 48px;text-align:center">
                        <input type="checkbox" id="selectAll" class="layui-form-checkbox" lay-skin="primary">
                    </th>
                    <th>报工类型</th>
                    <th>工作站</th>
                    <th>生产工单编号</th>
                    <th>产品物料编号</th>
                    <th>规格型号</th>
                    <th>报工数量</th>
                    <th>报工人</th>
                    <th>报工时间</th>
                    <th>审核人</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tb">
            </tbody>
        </table>
        <div id="pagination"></div>
    </div>
</body>
<script src="~/scripts/jquery-3.4.1.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
    var form; // 声明全局form变量
    var layer; // 声明全局layer变量
    
    // 初始化 layui 模块
    layui.use(['form', 'layer', 'table'], function(){
        form = layui.form;
        layer = layui.layer;
        var table = layui.table;

        // 绑定全选事件
        $(document).on('click', '#selectAll', function() {
            var isChecked = $(this).prop('checked');
            $('.row-checkbox').prop('checked', isChecked);
            form.render('checkbox');
        });

        // 绑定单个复选框事件
        $(document).on('click', '.row-checkbox', function() {
            var totalCheckboxes = $('.row-checkbox').length;
            var checkedCheckboxes = $('.row-checkbox:checked').length;
            $('#selectAll').prop('checked', totalCheckboxes === checkedCheckboxes);
            form.render('checkbox');
        });

        // 监听表单提交
        form.on('submit(searchForm)', function(data){
            Show();
            return false;
        });

        // 绑定批量删除按钮事件
        $('#batchDeleteBtn').on('click', function() {
            batchDelete();
        });

        // 初始化时渲染一次
        form.render('checkbox');
    });

    // 批量删除功能
    function batchDelete() {
        var checkedBoxes = $('.row-checkbox:checked');
        if (checkedBoxes.length === 0) {
            layer.msg('请选择要删除的记录', {icon: 2});
            return;
        }

        var ids = [];
        var hasNonDraftStatus = false;

        checkedBoxes.each(function() {
            var id = $(this).data('id');
            var tr = $(this).closest('tr');
            var status = tr.find('td:nth-child(11)').text().trim();

            if (status !== '草稿') {
                hasNonDraftStatus = true;
                return false;
            }

            if (id && !isNaN(id)) {
                ids.push(id);
            }
        });

        if (hasNonDraftStatus) {
            layer.msg('只能删除草稿状态的记录', {icon: 2});
            return;
        }

        if (ids.length === 0) {
            layer.msg('未找到有效的记录ID', {icon: 2});
            return;
        }

        layer.confirm('确定要删除选中的' + ids.length + '条记录吗？', {
            btn: ['确定', '取消'],
            title: '批量删除确认',
            icon: 3
        }, function() {
            var loading = layer.load(1);
            $.ajax({
                url: '/ProductionReport/BatchDeleteProductionReportingMain',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(ids),
                headers: {
                    'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                },
                success: function(res) {
                    layer.close(loading);
                    if (res > 0) {
                        layer.msg('成功删除' + res + '条记录', {
                            icon: 1,
                            time: 2000
                        }, function() {
                            // 重置全选框
                            $('#selectAll').prop('checked', false);
                            form.render('checkbox');
                            Show(); // 刷新表格
                        });
                    } else {
                        layer.msg('删除失败', {
                            icon: 2,
                            time: 2000
                        });
                    }
                },
                error: function(xhr, status, error) {
                    layer.close(loading);
                    console.error('批量删除失败:', xhr.responseText);
                    var errorMsg = '批量删除失败';
                    try {
                        var response = JSON.parse(xhr.responseText);
                        if (response.error && response.error.message) {
                            errorMsg += ': ' + response.error.message;
                        }
                    } catch(e) {}
                    layer.msg(errorMsg, {
                        icon: 2,
                        time: 2000
                    });
                }
            });
        });
    }

    function Show(){
        var loading = layer.load(1);
        try {
            var reportingType = $("#reportingType").val().trim();
            var workstationName = $("#workstationName").val().trim();
            var productionWorkOrderCode = $("#productionWorkOrderCode").val().trim();
            var productMaterialCode = $("#productMaterialCode").val().trim();
            var productMaterialName = $("#productMaterialName").val().trim();
            var reporter = $("#reporter").val().trim();
            var recorder = $("#recorder").val().trim();
            var states = $("#states").val().trim();
            
            $.ajax({
                url: "/ProductionReport/GetProductionReportingMain",
                type: "GET",
                data: {
                    reportingType: reportingType,
                    workstationName: workstationName,
                    productionWorkOrderCode: productionWorkOrderCode,
                    productMaterialCode: productMaterialCode,
                    productMaterialName: productMaterialName,
                    reporter: reporter,
                    recorder: recorder,
                    states: states,
                    sortField: "id",
                    sortOrder: "asc"
                },
                dataType: "json",
                success: function(res) {
                    layer.close(loading);
                    $("#tb").empty();
                    var data = [];
                    
                    if (res && res.data) {
                        data = res.data;
                    } else if (Array.isArray(res)) {
                        data = res;
                    } else if (res && res.Data) {
                        data = res.Data;
                    }

                    if(data && data.length > 0){
                        // 按照ID升序排序
                        data.sort(function(a, b) {
                            return a.id - b.id;
                        });

                        $.each(data, function(index, item){
                            var statusText = '';
                            switch(item.states) {
                                case 1:
                                    statusText = '草稿';
                                    break;
                                case 2:
                                    statusText = '审核中';
                                    break;
                                case 3:
                                    statusText = '已完成';
                                    break;
                                case 4:
                                    statusText = '已拒绝';
                                    break;
                                default:
                                    statusText = '';
                            }
                            
                            var reportingTime = item.reportingTime ? item.reportingTime.split('T')[0] : '';
                            
                            var row = `
                                <tr>
                                    <td style="text-align:center">
                                        <input type="checkbox" class="row-checkbox layui-form-checkbox" lay-skin="primary" data-id="${item.id || 0}">
                                    </td>
                                    <td>${item.reportingType || ''}</td>
                                    <td>${item.workstationName || ''}</td>
                                    <td>${item.productionWorkOrderCode || ''}</td>
                                    <td>${item.productMaterialName || ''}</td>
                                    <td>${item.productModel || ''}</td>
                                    <td>${item.reportingQuantity || ''}</td>
                                    <td>${item.reporter || ''}</td>
                                    <td>${reportingTime}</td>
                                    <td>${item.approver || ''}</td>
                                    <td>${statusText}</td>
                                    <td class="table-operations" data-id="${item.id || 0}">
                                        <div class="layui-btn-group">
                                            <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" onclick="deleteReport(${item.id})" ${item.states == 1 ? '' : 'style="display:none"'}>
                                                <i class="layui-icon layui-icon-delete"></i> 删除
                                            </button>
                                            <button type="button" class="layui-btn layui-btn-warm layui-btn-sm" onclick="editReport(${item.id})" ${item.states == 1 ? '' : 'style="display:none"'}>
                                                <i class="layui-icon layui-icon-edit"></i> 编辑
                                            </button>
                                            <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" onclick="viewReport(${item.id})">
                                                <i class="layui-icon layui-icon-form"></i> 查看
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            `;
                            $("#tb").append(row);
                        });

                        // 重新渲染表单元素
                        form.render('checkbox');
                        
                        // 重置全选框状态
                        $('#selectAll').prop('checked', false);
                        form.render('checkbox');
                    } else {
                        $("#tb").append('<tr><td colspan="12" style="text-align:center">暂无数据</td></tr>');
                    }
                },
                error: function(xhr, status, error) {
                    layer.close(loading);
                    console.error("Error:", error);
                    console.error("Status:", status);
                    console.error("Response:", xhr.responseText);
                    layer.msg('加载数据失败，请稍后重试', {icon: 2});
                }
            });
        } catch (e) {
            layer.close(loading);
            console.error("执行查询时发生错误:", e);
            layer.msg('查询出错，请稍后重试', {icon: 2});
        }
    }

    // 页面加载完成后执行初始查询
    $(function(){
        Show();
    });

    function resetForm() {
        $("#reportingType").val("");
        $("#workstationName").val("");
        $("#productionWorkOrderCode").val("");
        $("#productMaterialCode").val("");
        $("#productMaterialName").val("");
        $("#reporter").val("");
        $("#recorder").val("");
        $("#states").val("");
        
        if(form) {
            form.render(); // 重新渲染表单
        }
        
        Show();
    }

    function addProductionReport(){
        location.href = "/ProductionReport/ProductionReportAddView"
    }

    function viewReport(id) {
        if (!id) {
            layer.msg('无效的记录ID', {icon: 2});
            return;
        }
        location.href = `/ProductionReport/FindProductionReportAddView?id=${id}`;
    }

    function deleteReport(id) {
        if (!id) {
            layer.msg('无效的记录ID', {icon: 2});
            return;
        }
        
        layer.confirm('确定要删除这条记录吗？', {
            btn: ['确定', '取消']
        }, function() {
            var loading = layer.load(1);
            $.ajax({
                url: '/ProductionReport/DeleteProductionReportingMain?id=' + id,  // 修改为URL参数传递
                type: 'POST',
                headers: {
                    'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                },
                success: function(res) {
                    layer.close(loading);
                    console.log('删除响应:', res);
                    if (res === 0 || res === "0") {
                        layer.msg('删除失败', {
                            icon: 2,
                            time: 2000
                        });
                    } else {
                        layer.msg('删除成功', {
                            icon: 1,
                            time: 2000
                        }, function() {
                            Show(); // 刷新表格
                        });
                    }
                },
                error: function(xhr, status, error) {
                    layer.close(loading);
                    console.error('删除请求失败:', xhr.responseText);
                    layer.msg('删除失败，请稍后重试', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
        });
    }

    function editReport(id) {
        if (!id) {
            layer.msg('无效的记录ID', {icon: 2});
            return;
        }
        location.href = `/ProductionReport/UpdateProductionReportAddView?id=${id}`;
    }
</script>